package tree;

/**
 * @Description 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
 * @Author Firenut
 * @Date 2023-02-02 00:20
 */
public class T68_I_lowestCommonAncestor {

    // 法1: 递归
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root.val>p.val&&root.val>q.val){
            return lowestCommonAncestor(root.left,p,q);
        }else if(root.val<p.val&&root.val<q.val){
            return lowestCommonAncestor(root.right,p,q);
        }else{
            return root;
        }
    }

    // 法2 迭代
    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        while(root!=null){
            if(root.val>p.val&&root.val>q.val){
                root=root.left;
            }else if(root.val<p.val&&root.val<q.val){
                root=root.right;
            }else{
                return root;
            }
        }
        return root;
    }
}